package com.guqiao.library.net

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

import java.util.concurrent.TimeUnit


/**
 * @author jiangyao
 * @desc 网络操作工具类
 */
class RetrofitServiceManager private constructor() {

    private val DEFAULT_TIME_OUT = 5
    private val DEFAULT_READ_TIME_OUT = 10
    private val mBuilder: Retrofit.Builder
    private val DEFAULT_BASE_URL = "http://www.test.com/"

    init {

        val builder = OkHttpClient.Builder()
        /**
         * 连接超时时间
         */
        builder.connectTimeout(DEFAULT_TIME_OUT.toLong(), TimeUnit.SECONDS)
        /**
         * 读操作超时时间
         */
        builder.readTimeout(DEFAULT_READ_TIME_OUT.toLong(), TimeUnit.SECONDS)

        val commonInterceptor = HttpCommonInterceptor.Builder()
            .addHeaderParams("platform", "android")
            .build()
        builder.addInterceptor(commonInterceptor)

        mBuilder = Retrofit.Builder()
            .client(builder.build())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())

    }


    fun <T> create(baseUrl: String, service: Class<T>): T {
        return mBuilder.baseUrl(baseUrl).build().create(service)
    }


    fun <T> create(service: Class<T>): T {
        return create(DEFAULT_BASE_URL, service)
    }

    companion object {
        val instance = SingletonHolder.INSTANCE
    }

    private object SingletonHolder {
        val INSTANCE = RetrofitServiceManager()
    }
}
